package com.suoluo.zenapp.controllers;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.suoluo.zenapp.common.CommonResp;
import com.suoluo.zenapp.controllers.JSONInterceptor.JSON;
import com.suoluo.zenapp.service.ServiceException;

import net.paoding.rose.web.ControllerErrorHandler;
import net.paoding.rose.web.Invocation;

public class ErrorHandler implements ControllerErrorHandler {

	private static final Log logger = LogFactory.getLog(ErrorHandler.class);
	@Override
	public Object onError(Invocation inv, Throwable e) throws Throwable {
		// inv.isAnnotationPresent(arg0)
		if (inv.isAnnotationPresent(JSON.class)) {
			if (e instanceof ServiceException) {
				ServiceException se = (ServiceException) e;
				encodeToJSON(inv,new CommonResp(se.getResultCode(),
						se.getResultMsg()));
			} else {
				encodeToJSON(inv,CommonResp.FAIL);
			}
			logger.error("", e);
			return "";
		}
		return null;
	}

	private void encodeToJSON(Invocation invocation, Object encodeObj)
			throws IOException {
		HttpServletResponse response = invocation.getResponse();
		if (response.getContentType() == null) {
			response.setContentType("application/json;charset=UTF-8");
		}
		Gson gson = new Gson();

		String json = gson.toJson(encodeObj);
		response.getWriter().write(json);
	}

}
